package com.hzw.saas.service.user.service;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hzw.saas.api.property.IPropertyService;
import com.hzw.saas.api.property.enmus.SysDictKeyEnum;
import com.hzw.saas.api.user.ICustomerRefService;
import com.hzw.saas.api.user.IStaffService;
import com.hzw.saas.api.user.bo.StaffBO;
import com.hzw.saas.api.user.bo.StaffRoleBo;
import com.hzw.saas.common.config.util.MybatisPlusUtil;
import com.hzw.saas.common.config.util.PageParam;
import com.hzw.saas.common.config.util.PageUtils;
import com.hzw.saas.common.config.util.RedisUtil;
import com.hzw.saas.common.util.MapperUtil;
import com.hzw.saas.common.util.SnowFlakeUtil;
import com.hzw.saas.service.user.mapper.StaffMapper;
import com.hzw.saas.service.user.model.Staff;
import jodd.util.StringUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 *
 * </p>
 *
 * @author sonam
 * @since 2021/4/23 14:12
 */
@RequiredArgsConstructor
@Service("staffServiceImpl")
public class StaffServiceImpl extends ServiceImpl<StaffMapper, Staff> implements IService<Staff>, IStaffService {
    private final String CACHE_NAME = "seller";

    private final ICustomerRefService customerRefService;

    @Resource(name = IPropertyService.SYS_DICT_BEAN)
    private IPropertyService<SysDictKeyEnum> propertyService;

    @Resource(name = "staffServiceImpl")
    private IStaffService self;

    @Override
    public List<StaffBO> listByIds(List<String> ids) {
        if (Objects.isNull(ids)) {
            return new ArrayList<>();
        }
        List<Staff> staff = super.listByIds(ids);
        return MapperUtil.nf().mapAsList(staff, StaffBO.class);
    }

    @Override
    public List<StaffBO> query(StaffBO sellerBo) {
        List<Staff> sellers = this.list(Wrappers.<Staff>query().setEntity(MapperUtil.nf().map(sellerBo, Staff.class)));
        return MapperUtil.nf().mapAsList(sellers, StaffBO.class);
    }

    @Override
    public StaffBO queryOne(StaffBO staffBo) {
        List<StaffBO> staffBOS = self.query(staffBo);
        return CollectionUtils.isNotEmpty(staffBOS) ? staffBOS.get(0) : null;
    }

    @Override
    public StaffBO queryByPhoneNo(String phoneNo) {
        if (StrUtil.isBlank(phoneNo))
            return null;
        Staff staff = this.getOne(Wrappers.<Staff>lambdaQuery()
            .eq(Staff::getStaffPhoneNo, phoneNo).or()
            .eq(Staff::getStaffPhoneNo1, phoneNo).or()
            .eq(Staff::getStaffPhoneNo2, phoneNo));
        return MapperUtil.nf().map(staff, StaffBO.class);
    }

    @Override
    public StaffBO getByEmail(String email) {
        LambdaQueryChainWrapper<Staff> query = super.lambdaQuery()
            .eq(Staff::getStaffEmail, email);
        MybatisPlusUtil.limitOne(query);
        Staff one = query.one();
        return MapperUtil.nf().map(one, StaffBO.class);
    }

    @Override
    public IPage<StaffBO> searchByPage(PageParam pageParam, StaffBO sellerBo) {
        if (Objects.isNull(pageParam)) pageParam = new PageParam();
        Page<Staff> sellerPage = this.page(pageParam.convert(), Wrappers.<Staff>query().setEntity(MapperUtil.nf().map(sellerBo, Staff.class)));
        return PageUtils.convert(sellerPage, StaffBO.class);
    }

    @Override
    @Cacheable(cacheNames = {CACHE_NAME}, key = "#p0", condition = "#p0 != null")
    public StaffBO getById(String staffId) {
        if (StringUtil.isBlank(staffId)) return null;
        Staff seller = super.getById(staffId);
        return MapperUtil.nf().map(seller, StaffBO.class);
    }

    @Override
    @Transactional
    public void deleteByIds(List<String> staffIds) {
        if (CollectionUtils.isEmpty(staffIds)) {
            return;
        }
        this.removeByIds(staffIds);
        customerRefService.deleteByStaffIds(staffIds);
        RedisUtil.del(staffIds.toArray(new String[staffIds.size()]));
    }

    @Override
    @CacheEvict(cacheNames = {CACHE_NAME}, key = "#p0.pid")
    public void updateById(StaffBO staffBo) {
        Staff staff = MapperUtil.nf().map(staffBo, Staff.class);

        // 设置副手机号
        if (CollectionUtils.isNotEmpty(staffBo.getStaffPhoneNoList())) {
            if (staffBo.getStaffPhoneNoList().size() >= 1) {
                staff.setStaffPhoneNo1(staffBo.getStaffPhoneNoList().get(0));
            }
            if (staffBo.getStaffPhoneNoList().size() >= 2) {
                staff.setStaffPhoneNo2(staffBo.getStaffPhoneNoList().get(1));
            }
        }

        this.updateById(staff);
    }

    @Override
    public StaffBO addStaff(StaffBO staffBo) {
        Staff staff = MapperUtil.nf().map(staffBo, Staff.class);
        if (StringUtil.isBlank(staff.getPid())) {
            staff.setPid(String.valueOf(SnowFlakeUtil.nextId()));
        }

        // 设置副手机号
        if (CollectionUtils.isNotEmpty(staffBo.getStaffPhoneNoList())) {
            if (staffBo.getStaffPhoneNoList().size() >= 1) {
                staff.setStaffPhoneNo1(staffBo.getStaffPhoneNoList().get(0));
            }
            if (staffBo.getStaffPhoneNoList().size() >= 2) {
                staff.setStaffPhoneNo2(staffBo.getStaffPhoneNoList().get(1));
            }
        }

        this.save(staff);
        return MapperUtil.nf().map(staff, StaffBO.class);
    }

    @Override
    public IPage<StaffBO> likeSearchByPage(PageParam pageParam, StaffBO sellerBo) {
        Page<StaffRoleBo> iPage = pageParam.convert();
        Page<StaffRoleBo> staffPage = this.baseMapper.likeSearchByPage(iPage, sellerBo);

        IPage<StaffBO> staffBOPage = new Page<>(staffPage.getCurrent(), staffPage.getSize(), staffPage.getTotal(), staffPage.isSearchCount());
        staffBOPage.setRecords(new ArrayList<>());
        List<StaffBO> staffBOList = staffBOPage.getRecords();

        staffPage.getRecords().forEach(staff -> {
            StaffBO staffBO = MapperUtil.nf().map(staff, StaffBO.class);
            List<String> phoneNoList = new ArrayList<>();
            if (StringUtil.isNotBlank(staff.getStaffPhoneNo1()))
                phoneNoList.add(staff.getStaffPhoneNo1());
            if (StringUtil.isNotBlank(staff.getStaffPhoneNo2()))
                phoneNoList.add(staff.getStaffPhoneNo2());
            staffBO.setStaffPhoneNoList(phoneNoList);
            staffBOList.add(staffBO);
        });

        return staffBOPage;
    }

    @Override
    public StaffBO getDefaultStaffInfo() {
        StaffBO sellerBo = self.queryOne(new StaffBO().setIsDefault(1));

        if (Objects.nonNull(sellerBo)) {
            return sellerBo;
        }

        // 不存在则添加默认的销售到数据表中
        String defSellerName = propertyService.getPropertyValue(SysDictKeyEnum.SELLER_NAME, "鸿之微客服");
        String defSellerPhone = propertyService.getPropertyValue(SysDictKeyEnum.SELLER_PHONE, "021-50550302");
        String defSellerEmail = propertyService.getPropertyValue(SysDictKeyEnum.SELLER_EMAIL, "sales@hzwtech.com");
        sellerBo = new StaffBO()
            .setIsDefault(1)
            .setStaffName(defSellerName)
            .setStaffPhoneNo(defSellerPhone)
            .setStaffEmail(defSellerEmail);
        sellerBo.setPid(String.valueOf(SnowFlakeUtil.nextId()));

        self.addStaff(sellerBo);
        return sellerBo;
    }

}
